import traceback

from flask import request
from flask_restful import reqparse

from shop.conf import hot_words, VERSION_NUM, SHOP_API_URL, VERSION_INFO, goods_img_detail_prefix_time
from shop.handler.v2_handler import CollectionHandler
from shop.model.searchwords import save_one_searchwords
from shop.util.goods_operation import search_goods_v2, GoodsOperation
from shop.util.redis_util import RedisUtil
from shop.util.spider_taobao_goods_detail import get_goods_detail_by_itemurl_sellerid
from shop.util.string_operation import get_tkl_str
from shop.views.inherit_class import My_resource


class GoodsV2(My_resource):

    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument("page")
        self.parser.add_argument("kind")
        self.parser.add_argument('words')
        self.parser.add_argument('order')
        self.parser.add_argument("timestamp")
        self.parser.add_argument("hash_string")
        self.parser.add_argument("istmall")

    def put(self):
        args = self.parser.parse_args()
        args_page = int(args.get('page'))
        args_words = args.get('words')
        args_order = int(args.get('order', 3))
        istmall = int(args.get("istmall"))
        time_stamp = args.get("timestamp")
        hash_string = args.get("hash_string")
        # 验证ip黑名单
        is_black_ip = self.check_black_ip()
        if is_black_ip:
            return self.blacklisterror()
        # 验证秘钥
        res = self.check_hash(time_stamp, hash_string)
        if not res:
            return self.hasherror()
        # 把搜索关键词存入数据库中
        ip_addr = request.headers.get('X-Real-Ip')
        save_one_searchwords(args_words, ip_addr)
        goods_list = search_goods_v2(args_words, args_order, istmall, args_page)
        # 把搜索内容发送到微信
        # pool.submit(send_msg_to_weixin, ip_addr, args_words)
        return {
            "code": 200,
            "message": "success",
            "data": goods_list
        }


class HotWordsV2(My_resource):

    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument("timestamp")
        self.parser.add_argument("hash_string")

    def get(self):
        args = self.parser.parse_args()
        time_stamp = args.get("timestamp")
        hash_string = args.get("hash_string")
        # 验证ip黑名单
        is_black_ip = self.check_black_ip()
        if is_black_ip:
            return self.blacklisterror()
        # 验证秘钥
        res = self.check_hash(time_stamp, hash_string)
        if not res:
            return self.hasherror()
        return {
            "code": 200,
            "message": "success",
            "data": hot_words
        }


class VersionApiV2(My_resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument("timestamp")
        self.parser.add_argument("hash_string")

    def get(self):
        args = self.parser.parse_args()
        time_stamp = args.get("timestamp")
        hash_string = args.get("hash_string")
        res = self.check_hash(time_stamp, hash_string)
        if not res:
            return self.hasherror()
        version_num = VERSION_NUM
        shop_api_url = SHOP_API_URL
        version_info = VERSION_INFO
        # 验证ip黑名单
        is_black_ip = self.check_black_ip()
        if is_black_ip:
            return self.blacklisterror()

        return {
            "code": 200,
            "message": "成功",
            "data": {
                "version": version_num,
                "url": shop_api_url,
                "info": version_info,
            }
        }


class GoodImgDetailV2(My_resource):

    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument("timestamp")
        self.parser.add_argument("hash_string")
        self.parser.add_argument("item_url")

    def get(self):
        args = self.parser.parse_args()
        time_stamp = args.get("timestamp")
        hash_string = args.get("hash_string")
        item_url = args.get("item_url")
        # 验证参数是否为空
        if not all([time_stamp, hash_string, item_url]):
            return self.params_null_error()

        # 验证ip黑名单
        is_black_ip = self.check_black_ip()
        if is_black_ip:
            return self.blacklisterror()

        # 验证秘钥
        res = self.check_hash(time_stamp, hash_string)
        if not res:
            return self.hasherror()

        # 判断是否有缓存，如果有缓存，就读取缓存，否则，就请求，并设置缓存
        rdu = RedisUtil()
        redis_imgs_list = rdu.get_list(item_url)
        if redis_imgs_list:
            imgs_list = redis_imgs_list
        else:
            # 获取详情图片
            imgs_list = get_goods_detail_by_itemurl_sellerid(item_url)
            rdu.set_list(item_url, imgs_list, expire_second=goods_img_detail_prefix_time)

        return {
            "code": 200,
            "message": "success",
            "data": imgs_list
        }


class TklGoodsV2(My_resource):
    def post(self):
        '''
        获取淘口令商品
        :return:
        '''
        # 获取参数
        try:
            tkl_str = self.get_params(1, "tkl_str")
        except Exception as e:
            return self.error_dict.get(str(e))
        # 根据剪切板内容获取淘口令
        tkl = get_tkl_str(tkl_str)
        # 根据淘口令进行查询
        go = GoodsOperation()
        res = go.get_tkl_goods(tkl)
        data = go.format_tkl_goods_res(res)
        return self.success_return(data)


class CollectionViewV2(My_resource):
    def get(self):
        '''
        获取收藏
        :return:
        '''
        # 获取参数
        try:
            page, page_size = self.get_params(1, 'page', 'page_size')
            # 　验证token
            user_id = self.check_token()
            # 设置默认值
            if not page:
                page = 1
            if not page_size:
                page_size = 10
        except Exception as e:
            return self.error_dict.get(str(e))

        # 执行操作
        try:
            bh = CollectionHandler(user_id)
            # 执行保存用户浏览记录的操作
            data = bh.get_collection(page, page_size)
        except Exception as e:
            exception_detail = traceback.format_exc()
            self.logger.error(exception_detail)
            return self.error_return()
        return self.success_return(data)

    def post(self):
        '''
        收藏
        :return:
        '''
        # 获取参数
        try:
            goods_info = self.get_params(1, 'goods')
            # 　验证token
            user_id = self.check_token()
        except Exception as e:
            return self.error_dict.get(str(e))

        # 执行操作
        try:
            bh = CollectionHandler(user_id, goods_info)
            # 执行保存用户浏览记录的操作
            bh.save_collection()
        except Exception as e:
            exception_detail = traceback.format_exc()
            self.logger.error(exception_detail)
            return self.error_return()
        return self.success_return()
